package com.wannengbang.cloudleader;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.multidex.MultiDex;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.idst.nui.CommonUtils;
import com.alibaba.idst.nui.Constants;
import com.alibaba.idst.nui.INativeTtsCallback;
import com.alibaba.idst.nui.NativeNui;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.tencent.bugly.beta.ui.UILifecycleListener;
import com.tencent.bugly.crashreport.CrashReport;
import com.wannengbang.cloudleader.audioplayer.AudioPlayer;
import com.wannengbang.cloudleader.audioplayer.AudioPlayerCallback;
import com.wannengbang.cloudleader.audioplayer.Auth;
import com.wannengbang.cloudleader.audioplayer.Utils;
import com.wannengbang.cloudleader.utils.DisplayUtil;
import com.wannengbang.cloudleader.utils.VersionUtil;
import com.wannengbang.cloudleader.utils.SPManager;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;

public class MyApplication extends Application {

    private static final String TAG = "AliPushInit";
    private static Context context;
    private static Application application;

    private static String client_type;
    private static String client_version;
    private static String oem_no;
    private static String oem_app_id;
    private OutputStream output_file = null;
    private boolean b_savewav = false;
    private AudioPlayer mAudioTrack = null;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // 将MultiDex注入到项目中
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        context = getApplicationContext();

        mAudioTrack = new AudioPlayer(new AudioPlayerCallback() {
            @Override
            public void playStart() {
                Log.i(TAG, "start play");
            }

            @Override
            public void playOver() {
                Log.i(TAG, "play over");
            }
        });

        DisplayUtil.init(this);
        initParameter();
        initialize();
        if (!TextUtils.isEmpty(SPManager.getInstance().getProtocol())) {
            initCloudChannel(this);
            initCrashReport();
        }
    }

    public void initParameter() {
        //1-android 2-ios
        client_type = "1";
        client_version = String.valueOf(VersionUtil.packageName(getApplicationContext()));
        oem_no = "wannengbang";
        oem_app_id = "1";
    }


    public static Context getContext() {
        return context;
    }

    public static Application getApplication() {
        return application;
    }

    public static String getClient_type() {
        return client_type;
    }

    public static String getClient_version() {
        return client_version;
    }

    public static String getOem_no() {
        return oem_no;
    }

    public static String getOem_app_id() {
        return oem_app_id;
    }

    /**
     * 初始化语音播报
     *
     * @return
     */
    private int initialize() {
        String path = CommonUtils.getModelPath(this);
        //这里主动调用完成SDK配置文件的拷贝
        if (CommonUtils.copyAssetsData(this)) {
            Log.i(TAG, "copy assets data done");
        } else {
            Log.i(TAG, "copy assets failed");
        }
        int ret = NativeNui.GetInstance().tts_initialize(new INativeTtsCallback() {
            @Override
            public void onTtsEventCallback(INativeTtsCallback.TtsEvent event, String task_id, int ret_code) {
                Log.i(TAG, "tts event:" + event + " task id " + task_id + " ret " + ret_code);
                if (event == INativeTtsCallback.TtsEvent.TTS_EVENT_START) {
                    mAudioTrack.play();
                    Log.i(TAG, "start play");
                } else if (event == INativeTtsCallback.TtsEvent.TTS_EVENT_END) {
                    Log.i(TAG, "play end");
                    if (b_savewav) {
                        try {
                            output_file.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else if (event == TtsEvent.TTS_EVENT_PAUSE) {
                    mAudioTrack.pause();
                    Log.i(TAG, "play pause");
                } else if (event == TtsEvent.TTS_EVENT_RESUME) {
                    mAudioTrack.play();
                } else if (event == TtsEvent.TTS_EVENT_ERROR) {

                }
            }

            @Override
            public void onTtsDataCallback(String info, int info_len, byte[] data) {
                if (info.length() > 0) {
                    Log.i(TAG, "info: " + info);
                }
                if (data.length > 0) {
                    mAudioTrack.setAudioData(data);
                    Log.i(TAG, "write:" + data.length);
                    if (b_savewav) {
                        try {
                            output_file.write(data);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            @Override
            public void onTtsVolCallback(int vol) {
                Log.i(TAG, "tts vol " + vol);
            }
        }, genTicket(path), Constants.LogLevel.LOG_LEVEL_VERBOSE, true);

        if (Constants.NuiResultCode.SUCCESS != ret) {
            Log.i(TAG, "create failed");
        }
//        NativeNui.GetInstance().setparamTts("sample_rate", "16000");
//        NativeNui.GetInstance().setparamTts("font_name", "siqi");
//        NativeNui.GetInstance().setparamTts("enable_subtitle", "1");
//        NativeNui.GetInstance().setparamTts("speed_level", "1");
//        NativeNui.GetInstance().setparamTts("pitch_level", "0");
//        NativeNui.GetInstance().setparamTts("volume", "1.0");
        if (b_savewav) {
            try {
                output_file = new FileOutputStream("/sdcard/mit/tmp/test.pcm");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    private String genTicket(String workpath) {
        String str = "";
        try {
            //可以参考Auth类的实现通过阿里云Token获取SDK进行获取
            JSONObject object = Auth.getAliYunTicket();
            object.put("device_id", Utils.getDeviceId());
            object.put("url", "wss://nls-gateway.cn-shanghai.aliyuncs.com:443/ws/v1");
            object.put("workspace", workpath);
            str = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "UserContext:" + str);
        return str;
    }

    /**
     * 初始化云推送通道
     *
     * @param applicationContext
     */
    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.d(TAG, "init cloudchannel success deviceId : " + pushService.getDeviceId());
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.d(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
    }

    /**
     * 腾讯bugly
     */
    public void initCrashReport() {
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));

        Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog;
        Beta.upgradeDialogLifecycleListener = new UILifecycleListener<UpgradeInfo>() {
            @Override
            public void onCreate(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onCreate");
            }

            @Override
            public void onStart(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onStart");
            }

            @Override
            public void onResume(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onResume" + upgradeInfo.upgradeType);
                View view_line = view.findViewById(R.id.view_line);
                if (upgradeInfo.upgradeType == 2) {
                    view_line.setVisibility(View.GONE);
                }
            }

            @Override
            public void onPause(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onPause");
            }

            @Override
            public void onStop(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onStop");
            }

            @Override
            public void onDestroy(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onDestory");
            }
        };
        Bugly.init(getApplicationContext(), "d9689a1e7f", true);
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

}
